﻿using Digitalmes.Core.Common.PublishStrategies;
using Digitalmes.Core.Remotes;
using Digitalmes.Core.Services;

namespace Digitalmes.Core;

public static class ServiceCollectionExtensions
{
    /// <summary>
    /// 注入 Core 服务。
    /// </summary>
    /// <param name="builder"></param>
    /// <returns></returns>
    public static IHostBuilder UseCoreSetup(this IHostBuilder builder)
    {
        builder.ConfigureServices((hostBuilder, services) =>
        {
            services.AddMediatR();
            services.RegisterForInterfaceAndType<IApplicationService>(typeof(ServiceCollectionExtensions).Assembly, ServiceLifetime.Transient);
            services.RegisterForInterfaceAndType<IRemoteApi>(typeof(ServiceCollectionExtensions).Assembly, ServiceLifetime.Transient);
        });

        return builder;
    }

    /// <summary>
    /// 注册实现了 <see cref="ITransientServiceLifetime"/>、<see cref="IScopedServiceLifetime"/> 和 <see cref="ISingletonServiceLifetime"/> 的服务。
    /// </summary>
    /// <param name="services"></param>
    /// <param name="assembly">服务存在的程序集</param>
    public static void RegisterTypeServices(this IServiceCollection services, Assembly assembly)
    {
        services.RegisterForType<ITransientServiceLifetime>(assembly, ServiceLifetime.Transient);
        services.RegisterForType<IScopedServiceLifetime>(assembly, ServiceLifetime.Scoped);
        services.RegisterForType<ISingletonServiceLifetime>(assembly, ServiceLifetime.Singleton);
    }

    /// <summary>
    /// 注册 MediatR。
    /// </summary>
    /// <param name="services"></param>
    /// <param name="lifetime"></param>
    private static void AddMediatR(this IServiceCollection services, ServiceLifetime lifetime = ServiceLifetime.Transient)
    {
        services.AddMediatR(cfg =>
        {
            cfg.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly());

            cfg.Lifetime = lifetime;

            // 默认是框架自带的 ForeachAwaitPublisher，可以调整为 TaskWhenAllPublisher
            cfg.NotificationPublisher = PublishStrategyFactory.Create(PublishStrategy.ParallelNoWait); // 不能带任何任务结果
        });
    }
}
